﻿using System;
using System.Collections.Generic;

namespace DataScripter.Database.SqlServer
{
    public class SqlServerDatabaseStructure : IDatabaseStructure
    {
        private readonly IDictionary<string, ITableStructure> _tables = new Dictionary<string, ITableStructure>();
        private readonly SqlServerDb _db;

        public SqlServerDatabaseStructure(SqlServerDb db)
        {
            _db = db;
        }

        //public SqlServerDatabaseStructure(IEngine engine)
        //{
        //    _db = engine.Resolve<Db>();
        //}

        public string Instance
        {
            get { return _db.Instance; }
        }

        public string Database
        {
            get { return _db.Database; }
        }

        public ITableStructure GetTable(string tableName)
        {
            string[] strings = tableName.Split(".[]".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            string schemaName;
            if (strings.Length == 2)
            {
                schemaName = strings[0];
                tableName = strings[1];
            }
            else
            {
                schemaName = "dbo";
                tableName = strings[0];
            }
            return GetTable(schemaName, tableName);
        }

        public ITableStructure GetTable(string schemaName, string tableName)
        {
            string key = string.Format("[{0}].[{1}]", schemaName, tableName);
            if (!_tables.ContainsKey(key))
            {
                ITableStructure tableStructure = new SqlServerTableStructure(schemaName, tableName, _db);
                _tables.Add(key, tableStructure);
            }
            return _tables[key];
        }

        public IEnumerable<string> GetTableNames()
        {
            return _db.ExecuteEnumerable<string>(@"SELECT  '[' + sys.[schemas].[name] + '].[' + [sys].[tables].[name] + ']'
FROM    sys.[tables]
        INNER JOIN sys.[schemas] ON [sys].[tables].[schema_id] = [sys].[schemas].[schema_id]
        INNER JOIN sys.[objects] ON [sys].[tables].[object_id] = [sys].[objects].[object_id]
WHERE   [sys].[objects].[is_ms_shipped] = 0");
        }

        public override string ToString()
        {
            return _db.ToString();
        }
    }

}
